# Methods added to this helper will be available to all templates in the application.
module ApplicationHelper
  #override the button_to to support more data parameters
  #your specific data should start with 'post_'
  #
  #For example
  #	button_to("test", url_for({:controller=>'fragment',:action=>'vote', :id=>fragment}), :confirm => 'Are you sure?',
  #         :method => "post", :remote => true, :disable_with => 'loading...',:post_level=>1)
  #
  def button_to name, options = {}, html_options = {}
	value_tag = []
	html_options.each do |key, value|
		(value_tag << tag("input",{:type=>'hidden',:name=>key.to_s[/post_(.*)/,1],:value=>value})) if key.to_s.start_with?('post_')
	end
	form = super[/(.*)<\/div><\/form>/,1]
	"#{form}#{value_tag.join("")}</div></form>".html_safe
  end
  
  #Render step
  # 1: If the @sidebar variable is not nil, render it as the sidebar content
  # 2: If @sidevar is nil, render the _sidebar.html.erb at the controller's view folder.
  # 3: If can't find the _sidebar.html.erb in the controller's view folder, redner the _sidebar.html.erb at the layouts folder.
  # means render the global sidebar content.
  def content_for_sidebar
    content_for :sidebar  do
      @sidebar || contrller_level_sidebar
    end
  end

  #Any view can call this method to set the specific sidebar content

  def render_spedific_sidebar content
    @sidebar = content
  end

  def contrller_level_sidebar
    begin
      render :partial=>"sidebar"  #First find the action views/_sidebar.html.erb
    rescue
      render :partial=>"/layouts/sidebar"
    end
  end

  def get_login_user
    User.find session[:user_id] if session[:user_id]
  end

  def time_format time
    time.strftime("%Y-%m-%d %H:%M:%S");
  end

  def display_flash
    return if flash.empty?
    p = ""
    flash.each do |key, value|
      p <<(content_tag :p, value, :class=>"flash_#{key}")
    end
    (content_tag :div, p, {:id=>"flash"}, escape = false) << highlight('flash')
  end

  def highlight html_id
    content_tag :script, "new Effect.Highlight('#{html_id}',{ startcolor: '#FF0000',endcolor: '#FFFFFF',duration:2.0 });", :type=>"text/javascript"
  end

  #Help method for error handle

  def error_messages_for(*params)
    #add by glchengang
    key_hash = {}
    if params.first.is_a?(Hash)
      key_hash =  params.first
      params.delete_at(0)
    end
    #add end

    options = params.last.is_a?(Hash) ? params.pop.symbolize_keys : {}
    objects = params.collect {|object_name| instance_variable_get("@#{object_name}") }.compact
    count   = objects.inject(0) {|sum, object| sum + object.errors.count }
    unless count.zero?
      html = {}
      [:id, :class].each do |key|
        if options.include?(key)
          value = options[key]
          html[key] = value unless value.blank?
        else
          html[key] = 'errorExplanation'
        end
      end
      # change by glchengang
      #header_message = "有#{count}个错误"
      #header_message = "#{pluralize(count, 'error')} prohibited this #{(options[:object_name] || params.first).to_s.gsub('_', ' ')} from being saved"

      #add by glchengang
      error_messages = objects.map do |object|
        temp = []
        object.errors.each do |attr, msg|
          temp << content_tag(:li, msg)
        end
        html[:style]="color:red;"
        temp << highlight('errorExplanation')
      end
      #add end

      #error_messages = objects.map {|object| object.errors.full_messages.map {|msg| content_tag(:li, msg) } }
      content_tag(:div,
              #content_tag(options[:header_tag] || :h2, header_message) <<
      #content_tag(:p, 'There were problems with the following fields:') <<
      content_tag(:ul, error_messages, nil, escape=false), html, escape=false)
    else
      ''
    end
  end

  include ActsAsTaggableOn::TagsHelper #acts_as_tagging_on plugin helper
end
